import i18next from 'i18next'

import LanguageDetector from 'i18next-browser-languagedetector'

import en_US_common from './locales/en_US/common/common.json'
// import en_US_portal from './locales/en_US/portal/portal.json'
// import en_US_agent from './locales/en_US/agent/agent.json'
import en_US_assets from './locales/en_US/assets/assets.json'

import zh_CN_common from './locales/zh_CN/common/common.json'
// import zh_CN_portal from './locales/zh_CN/portal/portal.json'
// import zh_CN_agent from './locales/zh_CN/agent/agent.json'
import zh_CN_assets from './locales/zh_CN/assets/assets.json'
import { Languages } from './constants.js'

const resources = {}
resources[Languages.EN_US] = {
  translation: {
    common: en_US_common,
    // portal: en_US_portal,
    // agent: en_US_agent,
    assets: en_US_assets,
  }
}

resources[Languages.ZH_CN] = {
  translation: {
    common: zh_CN_common,
    // portal: zh_CN_portal,
    // agent: zh_CN_agent,
    assets: zh_CN_assets,
  }
}

// 调试：打印资源内容
console.log('加载的翻译资源:');
console.log('中文common资源:', zh_CN_common);
console.log('英文common资源:', en_US_common);
console.log('完整resources结构:', resources);

// 获取保存的语言设置
const savedLanguage = localStorage.getItem('i18nextLng') || Languages.ZH_CN;
console.log('初始化i18next，保存的语言:', savedLanguage);

// 重新配置i18next
i18next.init({
  resources,
  lng: savedLanguage,
  fallbackLng: Languages.ZH_CN,
  debug: false, // 关闭调试模式
  interpolation: {
    escapeValue: false
  },
  // 不使用命名空间
  defaultNS: 'translation',
  ns: ['translation']
}, (err, t) => {
  if (err) {
    console.error('i18next initialization error:', err);
    return;
  }
  // 移除调试输出，保持生产环境清洁
});

// 初始化函数（用于外部调用）
const initI18next = () => {
  return Promise.resolve();
};

export function t(key) {
  if (!i18next.isInitialized) {
    console.warn('i18next not initialized yet, returning key:', key);
    return key;
  }

  // 直接使用key进行翻译
  const result = i18next.t(key);

  if (result === key) {
    console.warn(`Translation missing for key: ${key}`);
    return key;
  }

  return result;
}

export function getCurrentLanguage() {
  return i18next.language
}

export function getSupportedLanguage() {
  return [Languages.ZH_CN, Languages.EN_US]
}

export { initI18next }

export function setLanguage(lng) {
  const currentLang = i18next.language
  if (currentLang === lng) {
    console.log('Language is already set to:', lng)
    return
  }

  return i18next.changeLanguage(lng, (err, t) => {
    if (err) return console.error(`Fail to change language: ${lng}`, err)
    console.log('current language:', lng)
    localStorage.setItem('i18nextLng', lng) // 手动缓存语言到localStorage
  })
}